package com.nari.ncps.screen.service.impl.electric;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.mapper.electric.ElectricSafetyenvPollutantMapper;
import com.nari.ncps.screen.service.electric.ElectricSafetyenvPollutantService;
import com.nari.ncps.screen.entity.electric.ElectricSafetyenvPollutant;
import com.nari.ncps.screen.vo.electric.MonthlyEmissionStatistics;
import com.nari.ncps.screen.vo.electric.MonthlyReductionStatistics;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 火电安全环保污染物表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-09-24
 */
@Service
public class ElectricSafetyenvPollutantServiceImpl extends ServiceImpl<ElectricSafetyenvPollutantMapper, ElectricSafetyenvPollutant> implements ElectricSafetyenvPollutantService {

    @Override
    public List<ElectricSafetyenvPollutant> getByYear(Integer year) {
        return baseMapper.selectByYear(year);
    }

    @Override
    public List<ElectricSafetyenvPollutant> getByYearAndMonth(Integer year, Integer month) {
        return baseMapper.selectByYearAndMonth(year, month);
    }

    @Override
    public ElectricSafetyenvPollutant getYearlyStatistics(Integer year) {
        return baseMapper.selectYearlyStatistics(year);
    }

    @Override
    public List<ElectricSafetyenvPollutant> getMonthlyTrend(Integer year) {
        QueryWrapper<ElectricSafetyenvPollutant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("year", year);
        queryWrapper.orderBy(true, true, "month"); // 按月份升序排列
        return list(queryWrapper);
    }

    @Override
    public ElectricSafetyenvPollutant getYearlyReductionBenefit(Integer year) {
        // 查询年度总的减排数据
        ElectricSafetyenvPollutant statistics = getYearlyStatistics(year);
        
        if (statistics != null) {
            // 创建一个新的对象，只包含减排相关数据
            ElectricSafetyenvPollutant reductionBenefit = new ElectricSafetyenvPollutant();
            reductionBenefit.setYear(year);
            reductionBenefit.setCo2Reduction(statistics.getCo2Reduction() != null ? statistics.getCo2Reduction() : BigDecimal.ZERO);
            reductionBenefit.setCoalSaving(statistics.getCoalSaving() != null ? statistics.getCoalSaving() : BigDecimal.ZERO);
            
            // 计算减排率（这里可以根据实际业务需求调整计算方式）
            if (statistics.getCo2Emission() != null && statistics.getCo2Emission().compareTo(BigDecimal.ZERO) > 0) {
                // 计算减排率并可以通过扩展字段或其他方式返回
                // BigDecimal reductionRate = statistics.getCo2Reduction()
                //     .divide(statistics.getCo2Emission().add(statistics.getCo2Reduction()), 4, RoundingMode.HALF_UP)
                //     .multiply(new BigDecimal("100"));
            }
            
            return reductionBenefit;
        }
        
        return null;
    }

    @Override
    public List<MonthlyEmissionStatistics> getRecentSixMonthsEmission(Integer year) {
        // 获取当前年月
        LocalDate now = LocalDate.now();
        int currentYear = now.getYear();
        int currentMonth = now.getMonthValue();
        
        // 如果传入了year参数
        if (year != null) {
            currentYear = year;
            // 如果传入的年份小于当前年份，使用12月；否则使用当前月份
            if (year < now.getYear()) {
                currentMonth = 12;
            }
            // 如果year等于当前年份，保持使用当前月份
        }
        
        // 计算起始月份（往前推6个月）
        int startYear = currentYear;
        int startMonth = currentMonth - 5;
        if (startMonth <= 0) {
            startYear = currentYear - 1;
            startMonth = 12 + startMonth;
        }
        
        // 声明为final以便在lambda中使用
        final int finalStartYear = startYear;
        final int finalStartMonth = startMonth;
        final int finalCurrentYear = currentYear;
        final int finalCurrentMonth = currentMonth;
        
        // 查询数据
        QueryWrapper<ElectricSafetyenvPollutant> queryWrapper = new QueryWrapper<>();
        if (startYear == currentYear) {
            // 同一年内
            queryWrapper.eq("year", finalCurrentYear)
                    .between("month", finalStartMonth, finalCurrentMonth);
        } else {
            // 跨年
            queryWrapper.and(wrapper -> wrapper
                    .and(w -> w.eq("year", finalStartYear).ge("month", finalStartMonth))
                    .or(w -> w.eq("year", finalCurrentYear).le("month", finalCurrentMonth))
            );
        }
        queryWrapper.orderByAsc("year", "month");
        
        List<ElectricSafetyenvPollutant> dataList = this.list(queryWrapper);
        
        // 按年月分组，汇总各电厂的数据
        Map<String, List<ElectricSafetyenvPollutant>> groupedData = dataList.stream()
                .collect(Collectors.groupingBy(item -> item.getYear() + "-" + item.getMonth()));
        
        // 转换为VO对象
        List<MonthlyEmissionStatistics> result = new ArrayList<>();
        for (Map.Entry<String, List<ElectricSafetyenvPollutant>> entry : groupedData.entrySet()) {
            List<ElectricSafetyenvPollutant> monthData = entry.getValue();
            if (monthData != null && !monthData.isEmpty()) {
                // 取第一条记录的年月
                ElectricSafetyenvPollutant first = monthData.get(0);
                
                // 汇总该月所有电厂的排放量
                BigDecimal totalCo2 = monthData.stream()
                        .map(item -> item.getCo2Emission() != null ? item.getCo2Emission() : BigDecimal.ZERO)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                
                BigDecimal totalSo2 = monthData.stream()
                        .map(item -> item.getSo2Emission() != null ? item.getSo2Emission() : BigDecimal.ZERO)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                
                MonthlyEmissionStatistics statistics = new MonthlyEmissionStatistics();
                statistics.setYear(first.getYear());
                statistics.setMonth(first.getMonth());
                statistics.setCo2Emission(totalCo2);
                statistics.setSo2Emission(totalSo2);
                statistics.setMonthName(first.getMonth() + "月");
                
                result.add(statistics);
            }
        }
        
        // 按年月排序
        result.sort((a, b) -> {
            int yearCompare = a.getYear().compareTo(b.getYear());
            if (yearCompare != 0) {
                return yearCompare;
            }
            return a.getMonth().compareTo(b.getMonth());
        });
        
        return result;
    }

    @Override
    public List<MonthlyReductionStatistics> getMonthlyReductionStatistics(Integer year) {
        // 如果year为空，使用当前年份
        if (year == null) {
            year = LocalDate.now().getYear();
        }
        
        // 查询指定年份的所有数据
        QueryWrapper<ElectricSafetyenvPollutant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("year", year)
                .orderByAsc("month");
        
        List<ElectricSafetyenvPollutant> dataList = this.list(queryWrapper);
        
        // 按月份分组，汇总各电厂的减排数据
        Map<Integer, List<ElectricSafetyenvPollutant>> groupedByMonth = dataList.stream()
                .collect(Collectors.groupingBy(ElectricSafetyenvPollutant::getMonth));
        
        // 转换为VO对象
        List<MonthlyReductionStatistics> result = new ArrayList<>();
        for (Map.Entry<Integer, List<ElectricSafetyenvPollutant>> entry : groupedByMonth.entrySet()) {
            Integer month = entry.getKey();
            List<ElectricSafetyenvPollutant> monthData = entry.getValue();
            
            // 汇总该月所有电厂的减排量
            BigDecimal totalCo2Reduction = monthData.stream()
                    .map(item -> item.getCo2Reduction() != null ? item.getCo2Reduction() : BigDecimal.ZERO)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            BigDecimal totalCoalSaving = monthData.stream()
                    .map(item -> item.getCoalSaving() != null ? item.getCoalSaving() : BigDecimal.ZERO)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            MonthlyReductionStatistics statistics = new MonthlyReductionStatistics();
            statistics.setYear(year);
            statistics.setMonth(month);
            statistics.setCo2Reduction(totalCo2Reduction);
            statistics.setCoalSaving(totalCoalSaving);
            statistics.setMonthName(month + "月");
            
            result.add(statistics);
        }
        
        // 按月份排序
        result.sort((a, b) -> a.getMonth().compareTo(b.getMonth()));
        
        return result;
    }
}
